interface ReplaceHandle<T> {
    (
        dataCache: NamedSet<T>,
        Map: Map<string, T>,
        oldKey: string,
        newData: T
    ): void;
}
export class NamedSet<T> extends Array<T> {
    constructor(
        private getKey: (input: T) => string,
        public repeatTag:
            | "ignore"
            | "cover"
            | "error"
            | ReplaceHandle<T> = "error"
    ) {
        super();
    }
    private Map = new Map<string, T>();
    push(...items: T[]) {
        items.forEach((i) => {
            const key = this.getKey(i);
            if (this.Map.has(key)) {
                if (typeof this.repeatTag === "string") {
                    switch (this.repeatTag) {
                        case "cover":
                            const item = this.Map.get(key)!;
                            const index = this.indexOf(item);
                            this.splice(index, 1);
                            this.Map.set(key, i);
                            super.push.call(this, i);
                            break;
                        case "error":
                            console.error(`已经有 ${key} 了`);
                        case "ignore":
                            break;
                    }
                } else {
                    this.repeatTag(this, this.Map, key, i);
                }
            } else {
                super.push.call(this, i);
                this.Map.set(key, i);
            }
        });

        return this.length;
    }
    pop(): T | undefined {
        const tail = super.pop.apply(this);
        if (tail) {
            const key = this.getKey(tail);
            this.Map.delete(key);
        }
        return tail;
    }
    get(key: string) {
        return this.Map.get(key);
    }
    /** 强制写入一个值 */
    set(value: T) {
        super.push.call(this, value);
        this.Map.set(this.getKey(value), value);
    }
    clear() {
        this.length = 0;
        this.Map.clear();
    }
}
